import StorageUtil from '../utils/StorageUtil';
import {Constant} from './Constant';
import HttpUtils from '../expand/dao/HttpUtils';
import {BASE_URL} from './BASE_URL';

const queryAllDictListUrl = BASE_URL.apiBaseUrl + '/api/dict/all';

export default class Dict {
  /**
   * 通过字典名获取字典
   * @param key 例如：'accident_class'
   * @returns {Promise<*>}
   */
  static async getDict(key) {
    const allDict = await StorageUtil.get(Constant.allDict);
    return allDict[key];
  }

  /**
   * 通过编号查询字典对应label，例如：3，较大事故
   * @param num 字段的编号
   * @param dict 字典
   * @returns {undefined}
   */
  static getLabelByDictNum(num, dict) {
    console.table('num', num, 'dict', dict);
    const obj = dict.find((item) => item.value === num.toString());
    return (obj && obj.label) || '暂无';
  }

  // 获取所有字典
  static getAllDict() {
    HttpUtils.request({
      url: queryAllDictListUrl,
      type: 'get',
    })
      .then((res) => {
        if (!res.status && res.length > 0) {
          const data = res;
          const dictObj = {};
          data.forEach((item) => {
            dictObj[item.name] = item.dictDetails;
          });
          StorageUtil.save(Constant.allDict, dictObj);
        }
      })
      .catch((e) => {
        console.log('请求字典：', e);
      });
  }
}
